package com.turing.data.scripts.yhjftzd.filter

import com.alibaba.fastjson.JSON
import com.turing.common.entity.TextVO
import com.turing.common.util.FileUtils
import com.turing.data.engine.utils.ScriptsUtils
import com.turing.data.vo.out.review.DependParamsVO
import com.turing.data.vo.out.review.TaskElementVO
import org.apache.commons.lang.SerializationUtils

/**
 * 场景名称: 外汇缴费通知单
 * 要素名称: 买卖类交易（手续费净额）
 * @author: fanyihang
 */

class BuyingAndSellingTransaction_30266_66_filter {

    static List< TaskElementVO.DrawResultVO > doConvert(DependParamsVO dependParams){

        List<TaskElementVO.DrawResultVO > resultVOs = ScriptsUtils.tryInitResult(dependParams)
        List<TaskElementVO.DrawResultVO> trueValueSet = new ArrayList<>()

        //子任务id
        def childTaskId = ""
        dependParams.getJSONTextMap().forEach({childTaskSn , jsonText ->
            childTaskId =childTaskSn
        })

        //依赖正则表达式
        String REGEX0 = /买卖类交易/
        def resultMatcherList = matching(dependParams,REGEX0,5)

        //行位置要小于关键词融券类交易的行位置
        String REGEX1 = /融券类交易/
        def keyWordMatcherList = matching(dependParams,REGEX1,0)

        if(resultMatcherList.size()>0){
            TaskElementVO.DrawResultVO defaultDrawResultVO = new TaskElementVO.DrawResultVO()
            //第一种情况（没有手续费净额，不存在5行）
            if(keyWordMatcherList.size()>0){
                if(keyWordMatcherList[0].lineStartIndex<resultMatcherList[0].lineStartIndex){
                    //匹配不到直接返回空字符串
                    defaultDrawResultVO.text = ""
                    trueValueSet.add(defaultDrawResultVO)
                    return trueValueSet
                }
            }
            //第二种情况
            //默认结果选第一个,对正则后的内容进行处理
            def originalText = resultMatcherList[0].objContent
            def getFinalReg = /\d.+\d/
            //处理返回的文本
            def matcherText = originalText =~ getFinalReg
            def finalText = originalText
            if(matcherText.count>0){
                finalText = matcherText[0]
                //设置返回的文本
                defaultDrawResultVO.text = finalText
                defaultDrawResultVO.businessValue = defaultDrawResultVO.text
                defaultDrawResultVO.childTaskSn = childTaskId
                defaultDrawResultVO.para_info  =  [resultMatcherList[0].lineId]
                //处理返回文本高亮
                //将处理后的正则结果和原来该行的所有内容进行正则匹配，找出起始位置，默认全文
                def positionMatcher = resultMatcherList[0].objContent =~ getFinalReg
                def positionStart = 0
                def positionEnd = originalText.length()
                while (positionMatcher.find()){
                    positionStart = positionMatcher.start()
                    positionEnd = positionMatcher.end()
                }
                defaultDrawResultVO.pos_info = [positionStart,positionEnd]
                defaultDrawResultVO.text = defaultDrawResultVO.text.replaceAll("，",",")
                trueValueSet.add(defaultDrawResultVO)
                return  trueValueSet
            }
        }


        //依赖模型，通过关键词返回值，返回值蒸汽率高，但无高亮，作为第二返回
        def REGEX_BACKUP_1 = "买卖类交易"

        if (resultVOs!=null && resultVOs.size()>0) {
            for (int i = 0; i < resultVOs.size(); i++) {
                def drawResultVO = resultVOs.get(i)
                def childTaskSn = drawResultVO.childTaskSn
                if(null == childTaskSn || childTaskSn == ""){
                    continue
                }
                def start = drawResultVO.start
                def end = drawResultVO.end
                def text = drawResultVO.text
                text = text.replaceAll("\n","")
                def textPathMap = dependParams.textPathMap
                def rawPath = textPathMap.get(drawResultVO.childTaskSn)
                def rawText = FileUtils.loadJson(rawPath)
                def expandOffset = 0
                //往前10个字符搜索
                while( expandOffset <= 30 && start > expandOffset ){
                    def expandString = rawText.substring(start-expandOffset,start)
                    if( expandString =~ REGEX_BACKUP_1)
                    {
                        trueValueSet.add(drawResultVO)
                        return trueValueSet
                    }
                    expandOffset  = expandOffset+10
                }
            }
        }

        //依赖正则
//        try{
//            if(trueValueSet.size()==0){
//                String REGEX = /(?<=买卖类交易[:：]).+?(?=[:：]融券类交易)/
//                dependParams.JSONTextMap.forEach(
//                        { childTaskSn, jsonText ->
//                            RegexExtract.doRuleExtract(REGEX,childTaskSn, dependParams, jsonText, trueValueSet)
//                        }
//                )
//                if(trueValueSet.size()>0){
//                    def textPathMap = dependParams.textPathMap
//                    def childTaskSn = trueValueSet[0].childTaskSn
//                    def rawPath = textPathMap.get(childTaskSn)
//                    def rawText = FileUtils.loadJson(rawPath)
//                    def JSONTextMap = dependParams.JSONTextMap
//                    def fileTextStr = ""
//                    fileTextStr = JSONTextMap.get(childTaskSn)
//                    def text = trueValueSet[0].text
//                    def startOffset = text.lastIndexOf(":")+1
//                    def enfOffset = 0
//                    //文本长度大于10，否则没有买卖交易手续费净额
//                    if(text.length()>10){
//                        TaskElementVO.DrawResultVO objectNew = (TaskElementVO.DrawResultVO) SerializationUtils.clone(trueValueSet[0])
//                        objectNew = TextUtils.correctPositionInfoByOffset(objectNew, startOffset, enfOffset, fileTextStr, rawText)
//                        objectNew.para_info = trueValueSet[0].para_info
//                        trueValueSet.clear()
//                        trueValueSet.add(objectNew)
//                        return trueValueSet
//                    }else {
//                        TaskElementVO.DrawResultVO defaultDrawResultVO = new TaskElementVO.DrawResultVO()
//                        defaultDrawResultVO.text = ""
//                        trueValueSet.clear()
//                        trueValueSet.add(defaultDrawResultVO)
//                        return  trueValueSet
//                    }
//                }
//            }
//        }
//        catch (Exception e){
//            e.printStackTrace()
//        }

        //返回空字符串
        TaskElementVO.DrawResultVO defaultDrawResultVO = new TaskElementVO.DrawResultVO()
        defaultDrawResultVO.text = ""
        trueValueSet.add(defaultDrawResultVO)
        return  trueValueSet

    }

    //通过正则获得一行内容
    static List<TextVO.Line> matching(DependParamsVO dependParams, String reg, int step){
        //返回结果的集合
        List<TextVO.Line> resultMatcherList = new ArrayList<>()
        //表格类型：通过json文本找到关键词的所在行
        dependParams.getJSONTextMap().forEach({ childTaskSn, jsonText ->
            List<TextVO> textVOList = JSON.parseArray(jsonText, TextVO.class)
            for (i in 0..<textVOList.size()) {
                //获得段落列表
                List<TextVO.Paragraph> listParagraph = textVOList[i].paragraphs
                for (j in 0..<listParagraph.size()) {
                    //获得每行的具体信息
                    List<TextVO.Line> lines = listParagraph[j].lines
                    for (k in 0..<lines.size()) {
                        //每行内容匹配关键词
                        def keyWordMatcher = lines[k].objContent =~ reg
                        if (keyWordMatcher.count > 0) {
                            //结果对象，关键词的下一局
                            resultMatcherList.add(lines[k + step])
                        }
                    }

                }
            }
        })
        return resultMatcherList
    }

}
